package main

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
	"grpc/demo/pb"
	"log"
	"net"
)

const Address = "127.0.0.1:9091"

type HiServer struct {
	pb.UnimplementedHelloServer
}

func (HiServer) SayHello(ctx context.Context, request *pb.HelloRequest) (*pb.HelloResponse, error) {
	log.Print("recv:", request.Name)
	return &pb.HelloResponse{Rsp: "Hello World"}, nil
}

func (HiServer) mustEmbedUnimplementedHelloServer() {
	//TODO implement me
	panic("implement me")
}

func main() {
	listen, err := net.Listen("tcp", Address)
	if err != nil {
		grpclog.Fatalf("Failed to listen: %v", err)
	}
	var opts []grpc.ServerOption
	opts = append(opts, grpc.UnaryInterceptor(interceptor))

	s := grpc.NewServer(opts...)
	var HelloService = HiServer{}
	pb.RegisterHelloServer(s, HelloService)
	grpclog.Infoln("Listen on " + Address)
	s.Serve(listen)
}

func interceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {

	log.Println("interceptor")
	err = auth(ctx)
	if err != nil {
		return nil, err
	}
	// 继续处理请求
	return handler(ctx, req)
}

func auth(ctx context.Context) error {
	return nil
}
